<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="员工姓名">
              <a-input placeholder="请输入员工姓名" v-model="queryParam.empName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="员工编号">
              <a-input placeholder="请输入员工编号" v-model="queryParam.empNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="性别">
              <j-dict-select-tag v-model="queryParam.sex" placeholder="请选择性别" dictCode="sex" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="手机号">
              <a-input placeholder="请输入手机号" v-model="queryParam.phone" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="所属部门">
              <j-tree-select
                ref="treeSelect"
                placeholder="请选择所属部门"
                v-model="queryParam.departId"
                dict="sys_depart,depart_name,id"
                pidField="parent_id"
                pidValue="0"
                hasChildField="has_child"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="入职日期">
              <j-date v-model="queryParam.hireDate" :showTime="false" dateFormat="YYYY-MM-DD" placeholder="请选择入职日期" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="工作状态">
              <j-dict-select-tag v-model="queryParam.workStatus" placeholder="请选择工作状态" dictCode="work_status" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
              <a-button style="margin-left: 8px" @click="handleToggleSearch" type="link">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'sys:employee:add'">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls" v-has="'sys:employee:export'">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
        v-has="'sys:employee:import'"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-has="'sys:employee:delete'">
            <a-icon type="delete"/>删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        
        <!-- 性别 -->
        <span slot="sexTitle">
          <a-tooltip placement="top">
            <template slot="title">
              <span>性别</span>
            </template>
            <a-icon type="user" />
          </a-tooltip>
        </span>
        <template slot="sexSlot" slot-scope="text">
          <j-dict-label :value="text" dictCode="sex"/>
        </template>
        
        <!-- 工作状态 -->
        <template slot="workStatusSlot" slot-scope="text">
          <j-dict-label :value="text" dictCode="work_status"/>
        </template>
        
        <!-- 操作按钮区域 -->
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-has="'sys:employee:edit'">编辑</a>
          <a-divider type="vertical" v-has="'sys:employee:edit'"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)" v-has="'sys:employee:query'">查看</a>
              </a-menu-item>
              <a-menu-item v-has="'sys:employee:delete'">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <employee-modal ref="modalForm" @ok="modalFormOk"></employee-modal>
  </a-card>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import EmployeeModal from './modules/EmployeeModal'
  import { filterObj } from '@/utils/util'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import JDate from '@/components/jeecg/JDate'
  import { getAction } from '@/api/manage'
  import { httpAction } from '@/api/manage'
  import { ACCESS_TOKEN } from '@/store/mutation-types'

  export default {
    name: "EmployeeList",
    mixins: [JeecgListMixin],
    components: {
      EmployeeModal,
      JDictSelectTag,
      JTreeSelect,
      JDate
    },
    data() {
      return {
        description: '员工管理页面',
        // 查询条件
        queryParam: {
          empName: '',
          empNo: '',
          sex: '',
          phone: '',
          departId: '',
          hireDate: '',
          workStatus: ''
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '员工编号',
            align: "center",
            dataIndex: 'empNo',
            width: 100
          },
          {
            title: '员工姓名',
            align: "center",
            dataIndex: 'empName',
            width: 100
          },
          {
            title: '性别',
            align: "center",
            dataIndex: 'sex',
            width: 80,
            scopedSlots: { customRender: 'sexSlot' }
          },
          {
            title: '手机号',
            align: "center",
            dataIndex: 'phone',
            width: 120
          },
          {
            title: '所属部门',
            align: "center",
            dataIndex: 'departName',
            width: 120
          },
          {
            title: '入职日期',
            align: "center",
            dataIndex: 'hireDate',
            width: 120,
            sorter: true
          },
          {
            title: '工作状态',
            align: "center",
            dataIndex: 'workStatus',
            width: 100,
            scopedSlots: { customRender: 'workStatusSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            width: 150,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/sys/employee/list",
          delete: "/sys/employee/delete",
          deleteBatch: "/sys/employee/deleteBatch",
          exportXlsUrl: "/sys/employee/exportXls",
          importExcelUrl: "sys/employee/importExcel"
        },
        toggleSearchStatus: true
      }
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      // 详情
      handleDetail(record) {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "详情";
        this.$refs.modalForm.disableSubmit = true;
      },
      // 导出
      handleExportXls() {
        let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()));
        let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`;
        
        // 使用axios下载文件，确保带上token
        const token = this.$ls.get(ACCESS_TOKEN);
        if (!token) {
          this.$message.warning('登录已过期，请重新登录');
          return;
        }
        
        const headers = { 'X-Access-Token': token };
        this.$http.get(url, { 
          responseType: 'blob',
          headers: headers
        }).then(response => {
          if (!response || response.size === 0) {
            this.$message.warning('导出失败，未获取到数据');
            return;
          }
          
          // 创建下载链接
          const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
          const fileName = `员工信息_${new Date().getTime()}.xls`;
          if (window.navigator.msSaveOrOpenBlob) {
            // IE浏览器下载
            navigator.msSaveBlob(blob, fileName);
          } else {
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
          }
        }).catch(err => {
          console.error('导出文件失败', err);
          this.$message.error('导出失败：' + (err.message || '未知错误'));
        });
      },
      // 导入
      handleImportExcel(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.$message.success(`${info.file.name} 文件上传成功`);
            this.loadData();
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
      },
      handleToggleSearch() {
        this.toggleSearchStatus = !this.toggleSearchStatus;
      }
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less';
</style> 